﻿using System;
using System.Data.SqlClient;

namespace HYFamilyLibDataManager
{
	public class SqlServerDatabase : FamilyLibDatabase
	{
		public ConnectData ConnectData
		{
			get
			{
				return this.mConnectData;
			}
		}

		public override string ConnStr
		{
			get
			{
				return string.Concat(new string[]
				{
					"Data Source=",
					this.mConnectData.IP,
					";Initial Catalog=",
					this.mName,
					";Integrated Security=False;User ID=",
					this.mConnectData.UserName,
					";Password=",
					this.mConnectData.Password,
					";Max Pool Size=10"
				});
			}
		}

		public SqlServerDatabase(string name, ConnectData cd)
		{
			this.mConnectData = cd;
			this.mName = name;
			this.Connection = new SqlConnection(this.ConnStr);
			this.Connection.Open();
		}

		public override ISubjectTable SubjectTable
		{
			get
			{
				return new SqlServerSubjectTable(this);
			}
		}

		public override ICategoryTable CategoryTable
		{
			get
			{
				return new SqlServerCategoryTable(this);
			}
		}

		public override ICategoryParamTable CategoryParamTable
		{
			get
			{
				return new SqlServerCategoryParamTable(this);
			}
		}

		public override IFamilyTable FamilyTable
		{
			get
			{
				return new SqlServerFamilyTable(this);
			}
		}

		public override IFamilyParamTable FamilyParamTable
		{
			get
			{
				return new SqlServerFamilyParamTable(this);
			}
		}

		public override ITypeTable TypeTable
		{
			get
			{
				return new SqlServerTypeTable(this);
			}
		}

		public override IFamilyFileTable FamilyFileTable
		{
			get
			{
				return new SqlServerFamilyFileTable(this);
			}
		}

		public override IFamilyImgTable FamilyImgTable
		{
			get
			{
				return new SqlserverFamilyImgTable(this);
			}
		}

		public static bool TestConnect(string server, string dbName, string uId, string pwd)
		{
			bool result;
			try
			{
				string connectionString = string.Format("Server ={0};Database ={1}; Uid ={2}; Pwd ={3};", new object[]
				{
					server,
					dbName,
					uId,
					pwd
				});
				SqlServerDatabase.tConn.ConnectionString = connectionString;
				SqlServerDatabase.tConn.Open();
				SqlServerDatabase.tConn.Close();
				SqlServerDatabase.tConn.Dispose();
				result = true;
			}
			catch
			{
				result = false;
			}
			return result;
		}

		private ConnectData mConnectData;

		private static SqlConnection tConn = new SqlConnection();
	}
}
